package com.cs.dingdingauto

import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.view.View
import android.view.WindowManager
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import com.cs.dingdingauto.databinding.ActivityMainBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.net.URLEncoder
import java.util.concurrent.TimeUnit


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        DingDingHelper.prepareNextLaunch()
        val binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        val refresh = {
            binding.etAtworkHours.setText(DingDingHelper.atWorkHours.toString())
            binding.etAtworkMin.setText(DingDingHelper.atWorkMin.toString())

            binding.etNoonHours.setText(DingDingHelper.atNoonHours.toString())
            binding.etNoonMin.setText(DingDingHelper.atNoonMin.toString())

            binding.etOffworkHours.setText(DingDingHelper.offWorkHours.toString())
            binding.etOffworkMin.setText(DingDingHelper.offWorkMin.toString())

            binding.etAtworkRandomMin.setText(DingDingHelper.atWorkRandomMin.toString())
            binding.etOffworkRandomMin.setText(DingDingHelper.offWorkRandomMin.toString())

            binding.newLaunch.isChecked = DingDingHelper.isNewLaunch
            binding.multiWindow.isChecked = DingDingHelper.isMultiWindow
            binding.skipWeekday.isChecked = DingDingHelper.isSkipWeekDay
        }
        refresh()
        binding.multiWindow.setOnCheckedChangeListener { buttonView, isChecked ->
            DingDingHelper.setMultiWindow(isChecked)
        }
        binding.newLaunch.setOnCheckedChangeListener { buttonView, isChecked ->
            DingDingHelper.setNewLaunch(isChecked)
        }
        binding.skipWeekday.setOnCheckedChangeListener { buttonView, isChecked ->
            DingDingHelper.setSkipWeekday(isChecked)
        }
        binding.btnUpdate.setOnClickListener {
            var etAtworkHours = binding.etAtworkHours.text.toString().trim().toLong()
            etAtworkHours = etAtworkHours.coerceAtLeast(0).coerceAtMost(23)
            var etAtworkMin = binding.etAtworkMin.text.toString().trim().toLong()
            etAtworkMin = etAtworkMin.coerceAtLeast(0).coerceAtMost(59)

            var etNoonHours = binding.etNoonHours.text.toString().trim().toLong()
            etNoonHours = etNoonHours.coerceAtLeast(0).coerceAtMost(23)
            var etNoonMin = binding.etNoonMin.text.toString().trim().toLong()
            etNoonMin = etNoonMin.coerceAtLeast(0).coerceAtMost(59)

            var atWorkRandomMin = binding.etAtworkRandomMin.text.toString().trim().toLong()
            var offWorkRandomMin = binding.etOffworkRandomMin.text.toString().trim().toLong()

            var etOffworkHours = binding.etOffworkHours.text.toString().trim().toLong()
            etOffworkHours = etOffworkHours.coerceAtLeast(0).coerceAtMost(23)
            var etOffworkMin = binding.etOffworkMin.text.toString().trim().toLong()
            etOffworkMin = etOffworkMin.coerceAtLeast(0).coerceAtMost(59)
            DingDingHelper.update(
                TimeUnit.HOURS.toMillis(etAtworkHours) + TimeUnit.MINUTES.toMillis(etAtworkMin),
                TimeUnit.HOURS.toMillis(etNoonHours) + TimeUnit.MINUTES.toMillis(etNoonMin),
                TimeUnit.HOURS.toMillis(etOffworkHours) + TimeUnit.MINUTES.toMillis(etOffworkMin),
                atWorkRandomMin,
                offWorkRandomMin)
            refresh()
        }
        binding.btnJumpToSettings.setOnClickListener {
//            AccessibilitySettingUtils.jumpToAccessibilitySetting(this)
            val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
            val uri: Uri = Uri.fromParts("package", packageName, null)
            intent.setData(uri)
            startActivity(intent)
        }
        binding.btnTest.setOnClickListener {
            val a = it.getCenterLocationInWindow()
            Toast.makeText(this, "I'm clicked %${a[0]} ${a[1]}", Toast.LENGTH_SHORT).show()
        }
        binding.btnDingdingTest.setOnClickListener { //            val a = it.getCenterLocationInWindow()
            //            Toast.makeText(this, "I'm clicked %${a[0]} ${a[1]}", Toast.LENGTH_SHORT).show()

            //            startDingtalkApp(this,"dingtalk://dingtalkclient/page/yunpan")
            val name = "com.alibaba.android.rimet"
            try {
                packageManager.getApplicationInfo(name, PackageManager.GET_UNINSTALLED_PACKAGES)
                val packageManager = packageManager
                val intent = packageManager.getLaunchIntentForPackage(name)
                application.startActivity(intent)
            } catch (e: PackageManager.NameNotFoundException) {
                Toast.makeText(this, "钉钉还没安装", Toast.LENGTH_SHORT).show()
            }
        }
        binding.btnLaunchTest.setOnClickListener {
            Toast.makeText(this, "请稍等，看3s- 1分钟半内能否调起应用自身", Toast.LENGTH_LONG).show()
            val intent = Intent(Intent.ACTION_MAIN)
            intent.addCategory(Intent.CATEGORY_HOME)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            startActivity(intent)
            val request = OneTimeWorkRequestBuilder<LaunchAppWork2>() // Additional configuration
                .addTag("launch_test")
                .setInitialDelay(4, TimeUnit.SECONDS).build()
            val code = WorkManager.getInstance(applicationContext).enqueue(request)

//                val intent = Intent(applicationContext,MainActivity::class.java)
//                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
//                applicationContext.startActivity(intent)
        }
        binding.btnLaunchCancel.setOnClickListener {
            DingDingHelper.cancelTask()
        }
    }

    @Throws(java.lang.Exception::class)
    private fun getAppInfo(context: Context) {
        val packageManager: PackageManager = context.getPackageManager() //获取所有安装的app
        val installedPackages = packageManager.getInstalledPackages(0)
        for (info in installedPackages) {
            val packageName = info.packageName //app包名
            val ai = packageManager.getApplicationInfo(packageName, 0)
            val appName = packageManager.getApplicationLabel(ai) as String //获取应用名称
        }
    }

    override fun onResume() {
        super.onResume()
        WorkManager.getInstance(applicationContext).cancelAllWorkByTag("launch_test")
    }

    fun openApp(context: Context, packageName: String?) {
        val intent = context.packageManager.getLaunchIntentForPackage(packageName!!)
        intent!!.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
        context.startActivity(intent)
    }

    fun View.getCenterLocationInWindow(): IntArray {
        val loc = IntArray(2)
        getLocationInWindow(loc)
        loc[0] += (width / 2f).toInt()
        loc[1] += (height / 2f).toInt()
        return loc
    }

    /**
     * 打开钉钉客户端 并在钉钉客户端打开传入的指定url
     * @param context 安卓上下文环境，推荐Activity Context
     * @param url 需要在钉钉客户端打开的页面地址
     */
    private fun startDingtalkApp(context: Context, url: String) {
        val intent = Intent(Intent.ACTION_VIEW)
        val jumpUrl = "dingtalk://dingtalkclient/page/link?url=" + URLEncoder.encode(url) //必须对url做encode
        val uri: Uri = Uri.parse(jumpUrl)
        intent.data = uri
        if (null != intent.resolveActivity(context.getPackageManager())) {
            context.startActivity(intent)
        }
    }
}